const express = require('express')
const router = express.Router()
const conn = require('../../model/mysql')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const fs = require('fs')
const saltRounds = 10;
router.get('/',(req,res,next)=>{
  res.send('测试用户路由接口!')
})
router.post('/login',(req,res,next)=>{
  let obj = req.body
  // console.log(req.body);
  // 先查询该手机号在数据库中是否是存在的
  conn.query('select * from users where u_phone = ?',[obj.u_phone],(err,result)=>{
    if(err){
      next(err)
      return
    }
    console.log(result);
    // 如果手机号存在 校验密码
    if(result.length>0){
      bcrypt.compare(obj.u_password, result[0].u_password, function(err, isTrue) {
          // isTrue == true?
          // 如果说匹配的密码是真,那么将生成token返回前台
          if(isTrue){
            // 生成一个token      
          var token = jwt.sign({
              data: obj.u_phone
            }, 'secret', { expiresIn: '24h' });
            // console.log(token);
            // 把生成的token返回给前台
            res.send({code:200,msg:'登录成功',"result":{"token":token,"u_name":result[0].u_name,"uphone":obj.u_phone,"uid":result[0].u_id}})
          }else{
            // 返回密码错误提示消息
            res.send({code:210,msg:'密码错误,请重新输入'})
          }
      });
    }else{
      // 数据库中没有该手机号,就告知用户去注册
      res.send({code:210,msg:'当前用户不存在，请前往注册!'})
    }
  })
})
router.post('/register',(req,res,next)=>{
  let obj = req.body
  console.log(obj);
  for(let k in obj){
    if(obj[k]==''){
      res.send({code:200,msg:`用户的${k}不能为空哦!`})
      return
    }
  }
  // 先查询数据库中是否已经存在用户的手机号
  conn.query('select * from users where u_phone = ?',[obj.u_phone],(err,result)=>{
    if(err){
      next(err)
      return
    }
    console.log(result);
    // 查询结果如果是空，说明数据库中不存在用户，可以进行注册操作
    if(result.length>0){
      res.send({code:210,msg:'当前用户已经存在，请使用手机号登录哦!'})
    }else{
      // 此时是空的，所以先进行密码加密处理
      bcrypt.genSalt(saltRounds, function(err, salt) {
        bcrypt.hash(obj.u_password, salt, function(err, hash) {
            // Store hash in your password DB.
           obj.u_password = hash
           conn.query('insert into users set ?',[obj],(err,result)=>{
             if(err){
               next(err)
               return
             }
             if(result.affectedRows>0){
               res.send({code:200,msg:'恭喜您注册成功,您可以去登录了!'})
             }else{
               res.send({code:210,msg:'注册失败,请稍后重试!'})
             } 
           })
        });
    });
    }
  })
})
router.get('/usermessage',(req,res,next)=>{
  console.log(req.query.u_phone);
  // 查询数据库，请求数据
  conn.query('select * from users where u_phone = ?',[req.query.u_phone],(err,result)=>{
    if(err){
      next(err)
      return
    }
    if(result.length>0){
      res.send({code:200,msg:'数据请求成功!',"result":result[0]})
    }else{
      res.send({code:210,msg:'数据请求失败!请稍后重试'})
    }
  })
})
// 往收藏表中插入数据
router.post('/addcollect',(req,res,next)=>{
  let obj = req.body
  console.log(obj)
  conn.query('insert into collect set ? ',[obj],(err,result)=>{
    if(err) return
    // if(err){
    //   next(err)
    //   return
    // }
    console.log(result);
  })
})
router.get('/collectlist',(req,res,next)=>{
  conn.query('select * from collect where u_id = ?',[req.query.u_id],(err,result)=>{
    if(err){
      next(err)
      return
    }
    if(result.length>0){
      res.send({code:200,msg:'数据请求成功!',"result":result})
    }else{
      res.send({code:210,msg:'数据请求失败!请稍后重试'})
    }
  })
})
// 用户的点赞和粉丝的添加。数量加1
router.post('/updateUsers',(req,res,next)=>{
  let fans = req.body.fans
  let sub = req.body.sub
  let uid = req.body.uid
  // 如果是粉丝加1
  if(fans==1){
    conn.query('select * from users where u_id = ?',[uid],(err,result)=>{
      if(err){
        next(err)
        return
      }
      if(result.length>0){
        let ufans = result[0].fans*1+1
        conn.query('update users set fans = ? where u_id = ?',[ufans,uid],(err,result)=>{
          if(err){
            next(err)
            return
          }
          if(result.affectedRows>0){
            res.send({code:200,msg:'ok'})
          }else{
            res.send({code:210,msg:'error'})
          }
        })
      }
    })
    // 否则就是减1
  }else{
    conn.query('select * from users where u_id = ?',[uid],(err,result)=>{
      if(err){
        next(err)
        return
      }
      if(result.length>0){
        let ufans = result[0].fans*1-1
        conn.query('update users set fans = ? where u_id = ?',[ufans,uid],(err,result)=>{
          if(err){
            next(err)
            return
          }
          if(result.affectedRows>0){
            res.send({code:200,msg:'ok'})
          }else{
            res.send({code:210,msg:'error'})
          }
        })
      }
    })
  }
  if(sub==1){
    conn.query('select * from users where u_id = ?',[uid],(err,result)=>{
      if(err){
        next(err)
        return
      }
      if(result.length>0){
        let subs = result[0].sub*1+1
        conn.query('update users set sub = ? where u_id = ?',[subs,uid],(err,result)=>{
          if(err){
            next(err)
            return
          }
          if(result.affectedRows>0){
            res.send({code:200,msg:'ok'})
          }else{
            res.send({code:210,msg:'error'})
          }
        })
      }
    })
  }else{
    conn.query('select * from users where u_id = ?',[uid],(err,result)=>{
      if(err){
        next(err)
        return
      }
      if(result.length>0){
        let subs = result[0].sub*1-1
        conn.query('update users set sub = ? where u_id = ?',[subs,uid],(err,result)=>{
          if(err){
            next(err)
            return
          }
          if(result.affectedRows>0){
            res.send({code:200,msg:'ok'})
          }else{
            res.send({code:210,msg:'error'})
          }
        })
      }
    })
  }
})
// 获取评论
router.get('/content',(req,res,next)=>{
  let uid = req.query.uid
  conn.query('select * from comment where uid = ?',[uid],(err,result)=>{
    if(err){
      next(err)
      return
    }
    res.send({code:200,result})
    // console.log(result[0].rec_id);
    // conn.query('select * from  recipe where id = ?',[result[0].rec_id],(err,result1)=>{
    //   if(err){
    //     next(err)
    //     return
    //   }
    //   res.send({code:200,result1})
    // })
  })
})
// 更新评论列表的like数据
router.get('/addcontentcount',(req,res,next)=>{
  conn.query('select like_num from recipe where id =?',[req.query.id],(err,result)=>{
    if(err){
      next(err)
      return
    }
     let num =  result[0].like_num*1+1
    conn.query('update recipe set like_num = ?',[num],(err,result)=>{
      if(err){
        next(err)
        return
      }
      res.send({code:200,result})
    })
  })
  
})
//详情接口
router.get('/detail', (req, res) => {
  console.log(req.query);
  let {rec_id,u_id}=req.query
  console.log('rec_id',rec_id);
  let result;
  //查询详情页的内容
  conn.query("select * from recipe where id = ? ",[rec_id], (err, res_detail) => {
    if (err) {
      return
    }
    if (!res_detail.length) {
      res.send({
        code: 201,
        msg: '啊偶,数据走丢了'
      })
      return;
    } else {
      result = res_detail[0]
      console.log('result.u_id',result.u_id);
      //查询关注状态
      conn.query("select * from user_rel where uid=? and rid=? and type=?", [u_id, result.u_id, 0], (err, res_relate) => {
        if (err) {
          return
        }
        if (!res_relate.length) {
          result.isSub = 0
        } else {
          result.isSub = 1
        }
        //查询菜谱作者信息
        conn.query("select u_name,avator from users where u_id =?",result.u_id,(err,res_info)=>{
          if(err) return
          result.uinfo={};
          result.uinfo.name=res_info[0].u_name
          result.uinfo.avatar=res_info[0].avator
        })
        //更新浏览历史
        let his_obj = {
          uid:u_id,
          rec_id,
          type: 0
        }
        conn.query("insert into brow_history set ?", his_obj, (err, res_his) => {
          if (err) {
            return
          }
          if (res_his.affectedRows == 1) {
            result.hisUpdateState = 1
          } else {
            result.hisUpdateState = 0
          }
          //查询配料
          conn.query("select * from ingred where rec_id=?", result.id, (err, res_ingred) => {
            if (err) {
              return
            }
            if (!res_ingred.length) {
              result.ingred = []
            } else {
              let ingred = [
                [],
                [],
                []
              ]
              console.log(res_ingred);
              res_ingred.forEach(item => {
                for (const key in item) {
                  if (item[key] == '主料') {
                    ingred[0].push(item)
                    continue;
                  } else if (item[key] == '辅料') {
                    ingred[1].push(item)
                    continue;
                  } else if(item[key] == '调味品'){
                    ingred[2].push(item)
                    continue;
                  }
                }
              });
              result.ingred = ingred;
              //查询菜谱大图信息
              conn.query("select main_img from main_imgs where rec_id=?",rec_id,(err,res_imgs)=>{
                if(err)return;
                console.log('大图信息',res_imgs);
                result.mainImg=[]
                result.mainImg=res_imgs
              })
              //查询收藏状态
              conn.query("select * from brow_history where uid=? and rec_id=? and type=?",[u_id,rec_id,2],(err,res_col)=>{
                if(err) return;
                if(!res_col.length){
                  result.collectState=0
                }else{
                  result.collectState=1
                }
              })
              //查询步骤
              conn.query("select * from step where rec_id=?", rec_id, (err, res_steps) => {
                if (err) {
                  return
                }
                if (!res_steps.length) {
                  result.steps = []
                } else {
                  result.steps = res_steps
                  //查询评论
                  conn.query("select * from comment where rec_id=? limit 5", rec_id, (err, res_comment) => {
                    if (err) {
                      return
                    }
                    if (!res_comment.length) {
                      result.comment = []
                    } else {
                      result.comment = res_comment
                      //查询评论中的点赞状态
                      let likeState=[]
                      res_comment.forEach((item,index)=>{
                        conn.query('select * from review_status where cid=? and uid=?',[item.id,u_id],(err,res_likes)=>{
                          if(err) return;
                          if(res_likes.length){
                            likeState.push(1)
                          }else{
                            likeState.push(0)
                          }
                          if(index==res_comment.length-1){
                            result.likeState=likeState
                            conn.query('select count(1) from comment  where rec_id=?',rec_id,(err,res_length)=>{
                              if(err) return;
                              console.log(res_length);
                              result.resLength=res_length[0]["count(1)"]
                              res.send({
                                code: 200,
                                msg: '查询成功',
                                result
                              })
                            })
                            
                          }
                        })
                      })
                    }
                  })
                }
              })
            }
          })
        })
      })
    }
  })
})

//详情中的点赞接口
router.get('/like', (req, res) => {
  console.log(req.query);
  let {
    cid,
    uid
  } = req.query
  var like_num=1;
  let result_com={};
  let like_obj = {
    uid,
    cid
  }
  conn.query('select * from review_status where cid=? and  uid=?', [cid, uid], (err, res_like) => {
    if (err) return;
    //未点赞的情况
    if (!res_like.length) {
      conn.query('insert into review_status set ?', like_obj, (err, res_dz) => {
        if (err) return;
        if (res_dz.affectedRows == 0) {
          res.send({
            code: 201,
            msg: '点赞失败'
          })
        } else {
          //更新评论表点赞数
          conn.query('select count(1) from review_status where cid=?',cid,(err,res_count)=>{
            like_num=res_count[0]['count(1)']
            console.log(like_num);
            conn.query('update comment set like_num=? where id=?',[like_num,cid] , (err, res_com) => {
              console.log('更新环节中的like',like_num);
              if (err) return;
              if (res_com.affectedRows == 1) {
                result_com.comState = '评论表点赞更新成功'
              } else {
                result_com.comState = '评论表点赞更新失败'
                res.send({code:201,msg:'点赞失败'})
                return;
              }
              res.send({code:200,msg:'点赞成功'})
            })
          })
        }
      })
    } 
    else {
    //已点赞的情况
      conn.query('delete from review_status where cid=? and  uid=?',[cid,uid],(err,res_liked)=>{
        if(err)return;
        if(res_liked.affectedRows==0){
          res.send({code:201,msg:'取消点赞失败'})
        }else{
          //取消点赞成功
          //更新评论表中的数据
          //查询点赞状态中的
          conn.query('select count(1) from review_status where cid=?',cid,(err,res_countt)=>{
            like_num=res_countt[0]['count(1)']
            console.log(like_num);
            conn.query('update comment set like_num=? where id=?',[like_num,cid],(err,res_cancel)=>{
              if(err) return;
              if(res_cancel.affectedRows==0){
                res.send({code:201,msg:'更新评论点赞失败'})
              }else{
                res.send({code:200,msg:'取消点赞成功'})
              }
            })
          })
        }
      })
    }
  })

})

//2021-12-20  21:31

//评论接口
router.get('/comment', (req, res) => {
  let {
    u_id,
    rec_id,
    offset
  } = req.query
  console.log(u_id);
  if(offset){
    //有偏移量的情况,分页
    let {offset}=req.query
    conn.query("select * from comment where rec_id=? limit ?,5", [rec_id,Number(offset)], (err, res_comment) => {
      if (err) {
        return
      }
      if (!res_comment.length) {
        res_comment = []
      } else {
        //查询评论中的点赞状态
        let likeState=[]
        res_comment.forEach((item,index)=>{
          conn.query('select * from review_status where cid=? and uid=?',[item.id,u_id],(err,res_likes)=>{
            if(err) return;
            if(res_likes.length){
              likeState.push(1)
            }else{
              likeState.push(0)
            }
            if(index==res_comment.length-1){
              res.send({
                code: 200,
                msg: '查询成功',
                result:{comment:res_comment,likeState}
              })
            }
          })
        })
      }
    })
  }else{
    let {txt,time}=req.query
    conn.query("select u_name,avator from users where u_id =?",[u_id],(err,res_user)=>{
      if(err) return
      console.log(res_user);
      let obj = {
        uid:u_id,
        rec_id,
        txt,
        upic:res_user[0].avator,
        time,
        uname:res_user[0].u_name
      }
      conn.query('insert into comment set ?', obj, (err, res_com) => {
        if (err) return;
        if (res_com.affectedRows == 0) {
          res.send({
            code: 201,
            msg: '评论失败'
          })
          return;
        } else {
        //评论成功
        //更新历史浏览表
        let browse_obj = {
          uid:u_id,
          rec_id,
          type: 3
        }
        conn.query('insert into brow_history set ?', browse_obj, (err, res_his) => {
          if (err) return;
          console.log(res_his);
          if (!res_his.affectedRows) {
            res.send({code:201,msg:'更新错误'})
          } else {
            //更新成功的情况
            conn.query("select * from comment where uid=? and time=?",[u_id,time],(err,res_back)=>{
              if(err) return;
              if(!res_back.length){
                res.send({code:201,msg:'数据出错啦!'})
              }else{
              console.log('res_back',res_back);
              res.send({code:200,msg:'评论成功',result:res_back[0]})
              }
            })
          }
        })
        
        }
      })
    })
  }
})

//关注接口
router.get('/sub',(req,res)=>{
  let {uid,ru_id}=req.query
  let subObj={
    uid,
    rid:ru_id,
    type:0
  }
  conn.query("select * from user_rel where uid=? and rid=? and type=?", [uid, ru_id, 0],(err,res_sub)=>{
    if(err) return;
    if(!res_sub.length){
      conn.query("insert into user_rel set ?",subObj,(err,updt_sub)=>{
        if(err) return;
        if(updt_sub.affectedRows==1){
          res.send({code:200,msg:'关注成功'})
        }else{
          res.send({code:201,msg:'关注失败'})
        }
      })
    }else{
      conn.query("delete from user_rel where uid=? and rid=? and type=?",[uid, ru_id, 0],(err,updt_sub)=>{
        if(err) return;
        if(updt_sub.affectedRows==1){
          res.send({code:200,msg:'取消关注成功'})
        }else{
          res.send({code:201,msg:'取消关注失败'})
        }
      })
    }
  })
})

//收藏接口
router.get('/collect',(req,res)=>{
  let{uid,rec_id}=req.query
  //查询账号id的收藏状态
  conn.query("select id from brow_history where uid=? and rec_id=? and type=?",[uid,rec_id,2],(err,res_col)=>{
    if(err) return;
    let c_num;
    conn.query('select clt_num from recipe where id=?',rec_id,(err,clt_num)=>{
      if(err) return;
      c_num=clt_num[0].clt_num;
    })
    console.log('res_col',res_col);
      //如果未收藏
      if(!res_col.length){
        //插入收藏数据
        let obj={
          uid,
          rec_id,
          type:2
        }
        conn.query("insert into brow_history set ?",obj,(err,updt_col)=>{
          if(err) return;         
          if(updt_col.affectedRows==1){
            //更新菜品表中的数据
            conn.query('update recipe set clt_num=? where id=?',[c_num+1,rec_id],(err,res_upcol)=>{
              if(err) return
              if(!res_upcol.affectedRows){
                res.send({code:201,msg:'收藏失败'})
              }else{
                res.send({code:200,msg:'收藏成功'})
              }
            })
            
          }else{
            res.send({code:201,msg:'更新失败'})
          }
        })
      }
      //如果已收藏
      else{
        //删除收藏数据
        conn.query("delete from brow_history where uid=? and rec_id=? and type=?",[uid, rec_id,2],(err,updt_col)=>{
          if(err) return;
          if(updt_col.affectedRows==1){
            //更新菜品表中的收藏数据
            conn.query('update recipe set clt_num=? where id=?',[c_num-1,rec_id],(err,res_upcol)=>{
              if(err) return
              if(!res_upcol.affectedRows){
                res.send({code:201,msg:'取消失败'})
              }else{
                res.send({code:200,msg:'取消收藏'})
              }
            })
          }else{
            res.send({code:201,msg:'取消失败'})
          }
        })
      }
    
    
  })
})




module.exports = router